document.addEventListener('click', event => {
    showWindowWithGroupsOfBooks(event);
    showGroupBooksWindow(event);
    closeWindowWithGroupsOfBooks(event);
})



function closeWindowWithGroupsOfBooks(event) {
    // Закрываем окно с группами книг

    if (!event.target.classList.contains('window-with-group-of-books-wrapper')) return;

    let groupBookList;
    let listOfBookGroups;

    if (groupBookList = document.querySelector('.group-books-window')) {
        groupBookList.remove();
    } else {
        document.querySelector('.window-with-group-of-books-wrapper').remove();
        document.querySelector('.book-groups').style.background = 'none';
        document.querySelector('.book-groups>a').style.color = 'white';
    }
}

function showGroupBooksWindow(event) {
    // Показываем окно с группой книг

    if (!event.target.closest('.group-card-link')) return;
    event.preventDefault();
    removeExtraWindow();

    const groupBooksWindow = getGroupBooksWindow();
    addData(groupBooksWindow);
    document.querySelector('.window-with-group-of-books-wrapper').insertAdjacentElement('beforeend', groupBooksWindow);


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function removeExtraWindow() {
        let groupBooksWindow;
        if (groupBooksWindow = document.querySelector('.group-books-window')) {
            groupBooksWindow.remove();
        }
    }

    function addData(groupBooksWindow) {
        const url = event.target.closest('.group-card-link').href;
        console.log('открываем', url)
        base.sendAjaxRequest(url, 'GET')
            .then(result => {
                insertData(groupBooksWindow, result);
            })
    }

    function insertData(groupBooksWindow, data) {
        const books = Object.values(data);
        for (let book of books) {
            book = Object.values(book);
            const linkToBook = getLinkToBook(book);
            const linkToImage = getLinkToImage(book);
            const bookDescription = getBookDescription(book);
            const bookHTML = `
                <a href="${linkToBook}" class="group-book">
                    <div class="image-group-book">
                        <img src="${linkToImage}">
                    </div>
                    <div class="additional-information-group-book">
                        <div class="title-group-book">
                            ${book[0]}
                        </div>
                        <div class="description-group-book">
                            ${bookDescription}
                        </div>
                    </div>
                </a>
            `
            groupBooksWindow.insertAdjacentHTML('beforeend', bookHTML);
        }

        showEmptyListOfBooks(books, groupBooksWindow)


        // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        function showEmptyListOfBooks(books, groupBooksWindow) {
            if (books.length == 0) {
                groupBooksWindow.innerHTML = `
                    <p class="empty-list-of-books" >В этой группе нет книг</p>
                `
            }
        }

        function getBookDescription(book) {
            const description = book[1];
            if (description) {
                return book[1].trim().split(' ').slice(0, 35).join(' ') + '...';
            } else {
                return 'Описание к книге не было добавлено'
            }
        }

        function getLinkToImage(book) {
            return '/media/' + book[2];
        }

        function getLinkToBook(book) {
            let link = book[3];
            link = document.location.origin + `/book/${link}`;
            return link;
        }
    }

    function getGroupBooksWindow() {
        const groupBooksWindow = document.createElement('div');
        groupBooksWindow.className = 'group-books-window';
        return groupBooksWindow;
    }
}

function showWindowWithGroupsOfBooks(event) {
    // Показываем окно с группами книг

    if (!event.target.closest('.book-groups')) return;
    event.preventDefault();
    changeAppearanceOfSelectedButton()

    const windowWithGroupsOfBooks = getWindowWithGroupsOfBooks();
    insertData(windowWithGroupsOfBooks);
    document.querySelector('.wrapper').insertAdjacentElement('beforeend', windowWithGroupsOfBooks)


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function changeAppearanceOfSelectedButton() {
        document.querySelector('.book-groups').style.background = 'white';
        document.querySelector('.book-groups>a').style.color = '#4c4c4c';
    }

    function insertData() {
        const url = document.location.origin + '/group/actions/?list_of_groups=true';
        base.sendAjaxRequest(url, 'GET')
            .then(result => {
                const listOfGroups = Object.values(result);

                for (const group of listOfGroups) {
                    const linkToGroup = document.location.origin + `/group/actions/?group=${group[1]}`;
                    const groupImage = getGroupImage(group[3]);
                    const groupDescription = getGroupDescription(group[2]);
                    const groupCard = `
                        <a href="${linkToGroup}" class="group-card-link">
                            <div class="group-card">
                                ${groupImage}
                                <div class="group-name">
                                    ${group[0]}
                                </div>
                                <div class="group-description">
                                    ${groupDescription}
                                </div>
                            </div>
                        </a>
                    `
                    document.querySelector('.window-with-group-of-books-inner').insertAdjacentHTML('beforeend', groupCard)
                }
            })

        function getGroupDescription(description) {
            if (description) {
                return description.trim().split(' ').slice(0, 25).join(' ') + '...';
            } else {
                return 'Описание не было добавлено'
            }
        }

        function getGroupImage(image) {
            if (image) {
                return `<div class="group-image group-card-empty-image">
                            <img src="/media/${image}">
                        </div>`
            } else {
                return `<div class="group-image group-card-empty-image">
                            <span>Изображение не установлено</span>
                        </div>`
            }
        }
    }
}

function getWindowWithGroupsOfBooks() {
    const windowWithGroupOfBooks = document.createElement('div');
    windowWithGroupOfBooks.className = 'window-with-group-of-books-wrapper';
    windowWithGroupOfBooks.innerHTML = `
        <div class="window-with-group-of-books-inner">
        </div>
    `
    return windowWithGroupOfBooks;
}